var app = require('express')();
var bodyParser = require('body-parser');
// normally you'd just do require('express-openapi'), but this is for test purposes.
var openapi = require('../../../');
var path = require('path');
var cors = require('cors');
var fs = require('fs');

app.use(cors());
app.use(bodyParser.json());

module.exports = async function () {
  await openapi.initialize({
    apiDoc: fs.readFileSync(path.resolve(__dirname, './api-doc.yml'), 'utf8'),
    app: app,
    promiseMode: true,
    paths: path.resolve(__dirname, 'api-routes'),
  });

  app.use(function (err, req, res, next) {
    res.status(err.status).json(err.message);
  });

  return app;
};

var port = parseInt(process.argv[2], 10);
if (port) {
  app.listen(port);
}
